package org.example;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.poi.ss.util.CellRangeAddress;
import org.example.entity.whlgd.*;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.FileOutputStream;
import java.io.IOException;
public class HttpRequestExample {

    public static void main(String[] args) {


        Workbook workbook= new XSSFWorkbook();
        Sheet  sheet = workbook.createSheet("Sheet1");
        // 创建 ObjectMapper 实例
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            // 请求的 URL
            String url = "https://wljy.whut.edu.cn/APermission/loadtree.ajax?searchValue=";
            String can ="id=ptype_-1&pId=SUPPER_PERMISSION_NODE&value=";
            ArrayList<Role> roles = (ArrayList<Role>)getResult(objectMapper, url,can);
            Integer rowIndex=0;

            for (Role role : roles){
                Integer initRowIndex=++rowIndex;
                Row row = sheet.createRow(rowIndex);
                Cell cell = row.createCell(0);
                cell.setCellValue(role.getName());
                ArrayList<Children> children = getChildren(objectMapper, url, role);
                if (children.isEmpty()){
                    Cell cell1 = row.createCell(1);
                    cell1.setCellValue("无");
                }
                Boolean first=true;
                for (Children child : children){
//睡眠100ms
                    Thread.sleep(100);
                    String url1="https://wljy.whut.edu.cn/APermission/nodeDetail.ajax";

                    ClickChildren result1 = (ClickChildren)getResult(objectMapper, url1, "nodeId="+child.getId());
                    ChildrenRecorder recorder = result1.getRecorder();
                    String url2="https://wljy.whut.edu.cn/system/AModule/navigation.ajax";
                    Thread.sleep(100);
                    DetailsObj result2=null;
                    if (recorder.getModuleNo()!=0){
                        result2 = (DetailsObj)getResult(objectMapper, url2, "pageNo=1&initCondition=1&condition=-1&pkValue="+recorder.getModuleNo());
                        System.out.println(result2);
                    }
                    if (first){
                        Cell cell1 = row.createCell(1);
                        Cell cell2 = row.createCell(2);
                        cell1.setCellValue(child.getName());
                        cell2.setCellValue(result2.getRecorder().getMenuPath());
                        first=false;
                    }else{
                        row = sheet.createRow(++rowIndex);
                        Cell cell1 = row.createCell(1);
                        Cell cell2 = row.createCell(2);
                        cell1.setCellValue(child.getName());
                        if (result2!=null){
                            cell2.setCellValue(result2.getRecorder().getMenuPath());
                        }else{
                            cell2.setCellValue("无");
                        }
                    }

                }
                if (rowIndex-initRowIndex!=0)
                sheet.addMergedRegion(new CellRangeAddress(initRowIndex, rowIndex, 0, 0));
                CellStyle style = getStyle(workbook);
                cell.setCellStyle(style);
            }
            // 输出到文件
            try (FileOutputStream fos = new FileOutputStream("C:\\Users\\QCY\\Desktop\\example_output.xlsx")) {
                workbook.write(fos);
                System.out.println("Excel 文件写入完成！");
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    workbook.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }




        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static ArrayList<Children> getChildren(ObjectMapper objectMapper, String url, Role role) throws Exception {
        // 请求体数据
        String requestBody2 = "id="+ role.getId()+"&pId=ptype_-1&value="; // 填入实际请求参数

        // 自定义请求头
        Map<String, String> headers2 = new HashMap<>();
        headers2.put("Accept", "application/json, text/javascript, */*; q=0.01");
        headers2.put("Accept-Encoding", "gzip, deflate, br, zstd");
        headers2.put("Accept-Language", "zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6");
        headers2.put("Cache-Control", "no-cache");
        headers2.put("Connection", "keep-alive");
        headers2.put("Content-Type", "application/x-www-form-urlencoded");
        headers2.put("Cookie", "USERLOGIN_USERNAME_COOKIE=wukaikui; USERLOGIN_USERPWD_COOKIE=IyQlcjY3OFkt; USERLOGIN_USERORG_COOKIE=00; USERLOGIN_USERLANG_COOKIE=\"\"; JSESSIONID=842C7AFBA69F8580DB038DDE77A1E84A");
        headers2.put("Host", "wljy.whut.edu.cn");
        headers2.put("Origin", "https://wljy.whut.edu.cn");
        headers2.put("Pragma", "no-cache");
        headers2.put("Referer", "https://wljy.whut.edu.cn/permissionManager.action?moduleId=PERMISION");
        headers2.put("Sec-Fetch-Dest", "empty");
        headers2.put("Sec-Fetch-Mode", "cors");
        headers2.put("Sec-Fetch-Site", "same-origin");
        headers2.put("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36 Edg/131.0.0.0");
        headers2.put("X-Requested-With", "XMLHttpRequest");
        headers2.put("sec-ch-ua", "\"Microsoft Edge\";v=\"131\", \"Chromium\";v=\"131\", \"Not_A Brand\";v=\"24\"");
        headers2.put("sec-ch-ua-mobile", "?0");
        headers2.put("sec-ch-ua-platform", "\"Windows\"");

        // 发送 POST 请求

        String response2 = sendPostRequest(url, headers2, requestBody2);
        //使用jackson 转化为 Response
        // 使用 TypeReference 来指定泛型类型
        ArrayList<Children> children = objectMapper.readValue(response2, new TypeReference<ArrayList<Children>>() {});
        return children;
    }

    private static Object getResult(ObjectMapper objectMapper, String url,String canshu) throws Exception {
        // 自定义请求头
        Map<String, String> headers1 = new HashMap<>();
        headers1.put("Accept", "application/json, text/javascript, */*; q=0.01");
        headers1.put("Accept-Encoding", "gzip, deflate, br, zstd");
        headers1.put("Accept-Language", "zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6");
        headers1.put("Cache-Control", "no-cache");
        headers1.put("Connection", "keep-alive");
        headers1.put("Content-Type", "application/x-www-form-urlencoded");
        headers1.put("Cookie", "USERLOGIN_USERNAME_COOKIE=wukaikui; USERLOGIN_USERPWD_COOKIE=IyQlcjY3OFkt; USERLOGIN_USERORG_COOKIE=00; USERLOGIN_USERLANG_COOKIE=\"\"; JSESSIONID=842C7AFBA69F8580DB038DDE77A1E84A");
        headers1.put("Host", "wljy.whut.edu.cn");
        headers1.put("Origin", "https://wljy.whut.edu.cn");
        headers1.put("Pragma", "no-cache");
        headers1.put("Referer", "https://wljy.whut.edu.cn/permissionManager.action?moduleId=PERMISION");
        headers1.put("Sec-Fetch-Dest", "empty");
        headers1.put("Sec-Fetch-Mode", "cors");
        headers1.put("Sec-Fetch-Site", "same-origin");
        headers1.put("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36 Edg/131.0.0.0");
        headers1.put("X-Requested-With", "XMLHttpRequest");
        headers1.put("sec-ch-ua", "\"Microsoft Edge\";v=\"131\", \"Chromium\";v=\"131\", \"Not_A Brand\";v=\"24\"");
        headers1.put("sec-ch-ua-mobile", "?0");
        headers1.put("sec-ch-ua-platform", "\"Windows\"");

        // 自定义请求体（你可以根据实际需求调整）
        String requestBody1 = canshu;

        // 发送 POST 请求
        String response1 = sendPostRequest(url, headers1, requestBody1);

        //判断返回值为对象还是集合
        if (response1.startsWith("{")) {
            // 返回值为对象
            try {
                ClickChildren clickChildren = objectMapper.readValue(response1, ClickChildren.class);
                return clickChildren;
            } catch (JsonProcessingException e) {
                DetailsObj detailsObj = objectMapper.readValue(response1, DetailsObj.class);
                return detailsObj;
            }
        } else if (response1.startsWith("[")) {
            // 返回值为集合
            ArrayList<Role> roles = objectMapper.readValue(response1, new TypeReference<ArrayList<Role>>() {});
            return roles;
        } else {
            // 返回值为其他类型，可以添加其他判断
            throw new Exception("返回值类型未知");
        }

    }

    /**
     * 发送 POST 请求的方法
     * @param urlString 请求的 URL
     * @param headers   自定义请求头
     * @param requestBody 请求体
     * @return 响应内容
     * @throws Exception
     */
    public static String sendPostRequest(String urlString, Map<String, String> headers, String requestBody) throws Exception {
        // 创建 URL 对象
        URL url = new URL(urlString);

        // 打开连接
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();

        // 设置请求方法为 POST
        connection.setRequestMethod("POST");



        // 设置请求头
        for (Map.Entry<String, String> header : headers.entrySet()) {
            connection.setRequestProperty(header.getKey(), header.getValue());
        }

        // 启用写入请求体
        connection.setDoOutput(true);

        // 写入请求体数据
        try (DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream())) {
            outputStream.writeBytes(requestBody);
            outputStream.flush();
        }

        // 获取响应代码
        int responseCode = connection.getResponseCode();
//        System.out.println("响应代码: " + responseCode);

        // 读取响应头
//        System.out.println("响应头信息：");
//        Map<String, List<String>> responseHeaders = connection.getHeaderFields();
//        for (Map.Entry<String, List<String>> entry : responseHeaders.entrySet()) {
//            System.out.println(entry.getKey() + ": " + entry.getValue());
//        }

        // 读取响应数据
        BufferedReader reader;
        if (responseCode >= 200 && responseCode < 300) {
            // 正常响应
            reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        } else {
            // 错误响应
            reader = new BufferedReader(new InputStreamReader(connection.getErrorStream()));
        }

        StringBuilder response = new StringBuilder();
        String line;
        while ((line = reader.readLine()) != null) {
            response.append(line);
        }
        reader.close();

        // 关闭连接
        connection.disconnect();

        // 返回响应数据
        return response.toString();
    }




    public static CellStyle getStyle(Workbook workbook){
        CellStyle style = workbook.createCellStyle();
        Font font = workbook.createFont();
        style.setFont(font);
        style.setAlignment(HorizontalAlignment.CENTER); // 水平居中
        style.setVerticalAlignment(VerticalAlignment.CENTER); // 垂直居中
        return style;
    }
}

